package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Emtity.*;
import com.itheima.common.BaseContext;
import com.itheima.common.*;
import com.itheima.mapper.OrderMapper;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;


    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
//        获得用户id
        Long userId = BaseContext.getCurrentId();

//        查询对应购物车数据
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);

        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomException("购物车为空,不能下单");
        }
//        自动生成订单号
        long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

//        获得购物车总金额.
        List<OrderDetail> collect = shoppingCartList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


//          查询用户数据
        User user = userService.getById(userId);
//        查询用户地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("地址为空,不能下单");
        }

//        向订单表插入数据,一条数据.
//        根据订单数据库,可以设置订单号,状态,用户订单


//      订单时间
        orders.setOrderTime(LocalDateTime.now());
//        结账时间
        orders.setCheckoutTime(LocalDateTime.now());
//        设置状态
        orders.setStatus(2);
//        总金额
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
//        订单号
        orders.setNumber(String.valueOf(orderId));
//        账号名字
        orders.setUserName(user.getName());
//        收货人真实名字
        orders.setConsignee(addressBook.getConsignee());
//        收货人电话
        orders.setPhone(addressBook.getPhone());
//        收货人地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) + (addressBook.getCityName() == null ? "" : addressBook.getCityName()) + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        this.save(orders);


//        向订单明细表数据插入数据.多条数据.
        orderDetailService.saveBatch(collect);

        //清空购物车数据.

        shoppingCartService.remove(lambdaQueryWrapper);


    }
}